using System;
using System.Data;
using System.Configuration;
using Pheonix.Fashionzoomer.DAL;
using System.Data.SqlClient;
using System.Collections;
using Pheonix.CodeLibrary.Data;
using Pheonix.CodeLibrary;

/// <summary>
/// Summary description for User
/// </summary>

namespace Pheonix.Fashionzoomer.Entity.SqlServer2000
{
    [System.ComponentModel.DataObject]
    public class User : SqlServerDAO
    {
        #region User Private Fields

		private Int32 _id;
		private String _userName;
		private String _userEmail;
		private String _userPassword;
		private Boolean _isActive;
		private Boolean _isVerified;
		private String _confirmationCode;
		private DateTime _lastVisit;
		private Int32 _membershipId;

        #endregion

        #region User Constractors

		public User(){}

		public User
		(
			Int32 id,
			String userName,
			String userEmail,
			String userPassword,
			Boolean isActive,
			Boolean isVerified,
			String confirmationCode,
			DateTime lastVisit,
			Int32 membershipId

		)
		{
			this._id = id;
			this._userName = userName;
			this._userEmail = userEmail;
			this._userPassword = userPassword;
			this._isActive = isActive;
			this._isVerified = isVerified;
			this._confirmationCode = confirmationCode;
			this._lastVisit = lastVisit;
			this._membershipId = membershipId;
		}

        #endregion

        #region User Properties

		public Int32 Id
		{
			get{ return this._id; }
			set{ this._id = value; }
		}

		public String UserName
		{
			get{ return this._userName; }
			set{ this._userName = value; }
		}

		public String UserEmail
		{
			get{ return this._userEmail; }
			set{ this._userEmail = value; }
		}

		public String UserPassword
		{
			get{ return this._userPassword; }
			set{ this._userPassword = value; }
		}

		public Boolean IsActive
		{
			get{ return this._isActive; }
			set{ this._isActive = value; }
		}

		public Boolean IsVerified
		{
			get{ return this._isVerified; }
			set{ this._isVerified = value; }
		}

		public String ConfirmationCode
		{
			get{ return this._confirmationCode; }
			set{ this._confirmationCode = value; }
		}

		public DateTime LastVisit
		{
			get{ return this._lastVisit; }
			set{ this._lastVisit = value; }
		}

		public Int32 MembershipId
		{
			get{ return this._membershipId; }
			set{ this._membershipId = value; }
		}


        #endregion

        #region User Static Methods

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static Int32 CreateNewUser
        (
			String userName,
			String userEmail,
			String userPassword,
			Boolean isActive,
			Boolean isVerified,
			String confirmationCode,
			DateTime lastVisit,
			Int32 membershipId

        )
        {
            //creating an empty User object
            User user = new User();
            user.UserName = userName;
			user.UserEmail = userEmail;
			user.UserPassword = userPassword;
			user.IsActive = isActive;
			user.IsVerified = isVerified;
			user.ConfirmationCode = confirmationCode;
			user.LastVisit = lastVisit;
			user.MembershipId = membershipId;

            return User.CreateNewUser(user);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool UpdateUser
        (
			Int32 id,
			String userName,
			String userEmail,
			String userPassword,
			Boolean isActive,
			Boolean isVerified,
			String confirmationCode,
			DateTime lastVisit,
			Int32 membershipId

        )
        {
            User user = User.GetUserById(id);
            user.UserName = userName;
			user.UserEmail = userEmail;
			user.UserPassword = userPassword;
			user.IsActive = isActive;
			user.IsVerified = isVerified;
			user.ConfirmationCode = confirmationCode;
			user.LastVisit = lastVisit;
			user.MembershipId = membershipId;

            return User.UpdateUser(user);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool DeleteUser
        (
            Int32 id
        )
        {
            //Validate Input
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in User"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_DELETEUSER);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);

        }

        public static bool DeleteUserList(System.Collections.Generic.List<Int32> idListToDelete)
        {
            //Validate Input
            foreach (Int32 id in idListToDelete)
                if (id <= GetIdMinValue)
                    throw (new ArgumentOutOfRangeException("id in User"));

            //performing deletion operation //

            string csvString = Utility.MakeCSV(idListToDelete);

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@IdList", SqlDbType.NVarChar, csvString.Length, 
                ParameterDirection.Input, csvString);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_DELETEUSERLIST);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == idListToDelete.Count ? true : false);
        }
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
		public static CustomCollection<User> GetUserByMembershipId(Int32 membershipId)
		{
			if(membershipId <= GetIdMinValue)
				throw (new ArgumentOutOfRangeException("membershipId in User"));

			SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@MembershipId", SqlDbType.Int, 0, ParameterDirection.Input, membershipId);
			SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_GETUSERBYMEMBERSHIPID);
			GenerateCollectionFromReader dg = new GenerateCollectionFromReader(GenerateUserCollectionFromReader);
			CustomCollection<User> objCollection = ((CustomCollection<User>)GetAllData(sqlCmd, dg));

			if (objCollection.Count > 0)
				return objCollection;
			else
				return null;
		}

        #endregion

        #region User Instance Methods
        
        public bool Save()
		{
			if(Id <= GetIdMinValue)
			{
				Int32 TempId=CreateNewUser(this);
				if(TempId>0)
				{
					_id=TempId;
					return true;
				}
				else
				{
					// error occurs
					return false;
				}
			}
			else
			{	//This is a update Command
				return (UpdateUser(this));
			}
		}

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<User> GetAllUser()
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_GETALLUSER);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateUserCollectionFromReader);
            CustomCollection<User> objCollection = ((CustomCollection<User>)GetAllData(sqlCmd, result));

            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<User> GetAllUserPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "Id";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startRowIndex", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@maximumRows", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_GETALLUSERPAGED);

            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateUserCollectionFromReader);
            CustomCollection<User> objCollection = ((CustomCollection<User>)GetAllData(sqlCmd, result));
            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllUserPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_GETALLUSERPAGEDCOUNT);
            GetOneData(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static User GetUserById(Int32 id)
        {
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in User"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_GETUSERBYID);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateUserCollectionFromReader);
            CustomCollection<User> objCollection = ((CustomCollection<User>)GetAllData(sqlCmd, result));

            if (objCollection.Count > 0)
                return (User)objCollection[0];
            else
                return null;
        }

        public static Int32 CreateNewUser(User newUser)
        {
            // validate Parameters
            if (newUser == null)
                throw (new ArgumentNullException("newUser in User"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@UserName", SqlDbType.NVarChar, 32, ParameterDirection.Input, newUser.UserName);
			AddParameterToSqlCmd(sqlCmd, "@UserEmail", SqlDbType.NVarChar, 64, ParameterDirection.Input, newUser.UserEmail);
			AddParameterToSqlCmd(sqlCmd, "@UserPassword", SqlDbType.NVarChar, 32, ParameterDirection.Input, newUser.UserPassword);
			AddParameterToSqlCmd(sqlCmd, "@IsActive", SqlDbType.Bit , 0, ParameterDirection.Input, newUser.IsActive);
			AddParameterToSqlCmd(sqlCmd, "@IsVerified", SqlDbType.Bit , 0, ParameterDirection.Input, newUser.IsVerified);
			AddParameterToSqlCmd(sqlCmd, "@ConfirmationCode", SqlDbType.NVarChar, 64, ParameterDirection.Input, newUser.ConfirmationCode);
			AddParameterToSqlCmd(sqlCmd, "@LastVisit", SqlDbType.DateTime, 0, ParameterDirection.Input, newUser.LastVisit);
			AddParameterToSqlCmd(sqlCmd, "@MembershipId", SqlDbType.Int, 0, ParameterDirection.Input, newUser.MembershipId);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_CREATENEWUSER);
            GetOneData(sqlCmd);
            return ((Int32)sqlCmd.Parameters["@ReturnValue"].Value);

        }

        public static bool UpdateUser(User newUser)
        {
            // validate Parameters
            if (newUser == null)
                throw (new ArgumentNullException("newUser"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, newUser.Id);
            AddParameterToSqlCmd(sqlCmd, "@UserName", SqlDbType.NVarChar, 32, ParameterDirection.Input, newUser.UserName);
			AddParameterToSqlCmd(sqlCmd, "@UserEmail", SqlDbType.NVarChar, 64, ParameterDirection.Input, newUser.UserEmail);
			AddParameterToSqlCmd(sqlCmd, "@UserPassword", SqlDbType.NVarChar, 32, ParameterDirection.Input, newUser.UserPassword);
			AddParameterToSqlCmd(sqlCmd, "@IsActive", SqlDbType.Bit , 0, ParameterDirection.Input, newUser.IsActive);
			AddParameterToSqlCmd(sqlCmd, "@IsVerified", SqlDbType.Bit , 0, ParameterDirection.Input, newUser.IsVerified);
			AddParameterToSqlCmd(sqlCmd, "@ConfirmationCode", SqlDbType.NVarChar, 64, ParameterDirection.Input, newUser.ConfirmationCode);
			AddParameterToSqlCmd(sqlCmd, "@LastVisit", SqlDbType.DateTime, 0, ParameterDirection.Input, newUser.LastVisit);
			AddParameterToSqlCmd(sqlCmd, "@MembershipId", SqlDbType.Int, 0, ParameterDirection.Input, newUser.MembershipId);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_USER_UPDATEUSER);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);
        }

        #endregion

        #region User Related Collections
        /// <summary>
        /// Creates and returns a strongly typed collection of User custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains 
        /// User information, as a set of records, similar to tabular format.
        /// </summary>
        public static IList GenerateUserCollectionFromReader(IDataReader returnData)
        {

            //creating the instance of User collection
            CustomCollection<User> colUser = new CustomCollection<User>();

            //Iterating thriugh the data reader, to generate User collection.

            //getting the User collection by iterating thru the data reader
            while (returnData.Read())
            {
                //passing the User constructor parameters from the current instance of data reader fields.
                User newUser = new User
                (
                    returnData["id"] == System.DBNull.Value ? GetIdMinValue : (Int32)returnData["id"],
                    returnData["user_name"] == System.DBNull.Value ? String.Empty : (String)returnData["user_name"],
					returnData["user_email"] == System.DBNull.Value ? String.Empty : (String)returnData["user_email"],
					returnData["user_password"] == System.DBNull.Value ? String.Empty : (String)returnData["user_password"],
					returnData["is_active"] == System.DBNull.Value ? false : (Boolean)returnData["is_active"],
					returnData["is_verified"] == System.DBNull.Value ? false : (Boolean)returnData["is_verified"],
					returnData["confirmation_code"] == System.DBNull.Value ? String.Empty : (String)returnData["confirmation_code"],
					returnData["last_visit"] == System.DBNull.Value ? DateTime.MinValue : (DateTime)returnData["last_visit"],
					returnData["membership_id"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["membership_id"]

                );
                //adding the User to the collection
                colUser.Add(newUser);
            }

            //returns the collection of User 
            return (colUser);
        }

        #endregion

        #region Constants and Default Values

        public static Int32 GetIdMinValue
        {
            get
            {
                return 0;
            }
        }

        //contants
        internal const string SPR_USER_CREATENEWUSER = "spr_User_CreateNewUser";
        internal const string SPR_USER_UPDATEUSER = "spr_User_UpdateUser";
        internal const string SPR_USER_DELETEUSER = "spr_User_DeleteUser";
        internal const string SPR_USER_DELETEUSERLIST = "spr_User_DeleteUserList";
        internal const string SPR_USER_GETUSERBYID = "spr_User_GetUserById";
        internal const string SPR_USER_GETALLUSER = "spr_User_GetAllUser";
        internal const string SPR_USER_GETALLUSERPAGED = "spr_User_GetAllUserPaged";
        internal const string SPR_USER_GETALLUSERPAGEDCOUNT = "spr_User_GetAllUserPagedCount";

		//Foreign key contants
		internal const string SPR_USER_GETUSERBYMEMBERSHIPID="spr_User_GetUserByMembershipId";
		internal const string SPR_USER_GETUSERBYMEMBERSHIPIDPAGED="spr_User_GetUserByMembershipIdPaged";
		internal const string SPR_USER_GETUSERBYMEMBERSHIPIDPAGEDCOUNT="spr_User_GetUserByMembershipIdPagedCount";
		
        #endregion
    }
}
